import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join, resolve } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  let lostFocus = false
  let isMinimized = false
  const miniIn = false

  mainWindow.on('minimize', (e) => {
    e.preventDefault()
    if (!isMinimized) {
      mainWindow.setOpacity(0)
      isMinimized = true
      setTimeout(() => {
        if (isMinimized) {
          mainWindow.restore()
        }
      }, 0)
    } else {
      mainWindow.setOpacity(1)
      isMinimized = false
    }
  })

  mainWindow.on('focus', () => {
    if (isMinimized && mainWindow.getOpacity() === 0 && lostFocus) {
      lostFocus = false
      console.log('0--0-')
      console.log('1--1-')
    }
  })

  mainWindow.on('blur', () => {
    lostFocus = true
  })

  //用户点击了最小化
  ipcMain.on('click-mini', () => {
    mainWindow.minimize()
  })

  //任务栏的图标用户点击了怎么处理

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  console.log('111')
})
